﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace WpfScratchApp
{
    public class Command : ICommand
    {
        private Timer _timer;
        private bool _canExecute = true;
        private readonly Dispatcher _dispatcher;

        public Command(Dispatcher dispatcher)
        {
            _dispatcher = dispatcher;
        }
        
        public void Execute(object parameter)
        {
            _canExecute = false;
            CanExecuteChanged(this, new EventArgs());

            _timer = new Timer(TimerExpired, null, 1000, Timeout.Infinite);
        }

        private void TimerExpired(object state)
        {
            _timer.Dispose();
            _timer = null;
            _canExecute = true;
            _dispatcher.BeginInvoke((Action)(() => CanExecuteChanged(this, new EventArgs())));
        }

        public bool CanExecute(object parameter)
        {
            return _canExecute;
        }

        public event EventHandler CanExecuteChanged;
    }

    /// <summary>
    /// Interaction logic for CommandBindingTest.xaml
    /// </summary>
    public partial class CommandBindingTest : Window
    {
        private readonly ICommand _command;

        public CommandBindingTest()
        {
            InitializeComponent();
            _command = new Command(Dispatcher);
            DataContext = this;
        }

        public ICommand MyCommand
        {
            get { return _command; }
        }
    }
}
